package com.desire.test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @author desire
 */
public class _41_多个线程执行_一个线程收尾 {
    static CountDownLatch latch = new CountDownLatch(5);

    public static void main(String[] args) {
        var t = new _41_多个线程执行_一个线程收尾();
        // 同时开启4个工作线程,一个main线程 一个结束程序线程
        new Thread(t::work1, "T1").start();
        new Thread(t::work2, "T2").start();
        new Thread(t::work3, "T3").start();
        new Thread(t::work4, "T4").start();
        new Thread(t::over, "OVER").start();

        // main 线程执行 打印名字
        try {
            System.out.println(Thread.currentThread().getName() + "工作线程启动...");
            TimeUnit.SECONDS.sleep(1);
            System.out.printf("%s%n", Thread.currentThread().getName());
            for (int i = 0; i < 10; i++) {
                TimeUnit.SECONDS.sleep(1);
                System.out.printf("%d ", i);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        latch.countDown();
    }


    // 工作线程执行打印名字
    void work1() {
        System.out.println(Thread.currentThread().getName() + "工作线程启动...");
        try {
            TimeUnit.SECONDS.sleep(1);
            System.out.printf("%s%n", Thread.currentThread().getName());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 开启门栓 提醒另一个线程等待结束
        latch.countDown();
    }

    void work2() {
        System.out.println(Thread.currentThread().getName() + "工作线程启动...");
        try {
            for (int i = 0; i < 10; i++) {
                TimeUnit.SECONDS.sleep(1);
                System.out.printf("%s ", "*");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 开启门栓 提醒另一个线程等待结束
        latch.countDown();
    }

    void work3() {
        System.out.println(Thread.currentThread().getName() + "工作线程启动...");
        try {
            for (int i = 0; i < 10; i++) {
                TimeUnit.SECONDS.sleep(1);
                System.out.printf("%s ", "/");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 开启门栓 提醒另一个线程等待结束
        latch.countDown();
    }

    void work4() {
        System.out.println(Thread.currentThread().getName() + "工作线程启动...");
        try {
            for (int i = 0; i < 10; i++) {
                TimeUnit.SECONDS.sleep(1);
                System.out.printf("%s ", "※");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 开启门栓 提醒另一个线程等待结束
        latch.countDown();
    }


    // 收尾线程 监控 当工作线程和main线程 执行结束时 打印程序结束
    void over() {
        System.out.println("收尾线程启动....");
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("\n" + Thread.currentThread().getName() + "收尾程序结束");

    }
}
